package com.farvision.common.log;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.json.JSONUtil;
import com.farvision.common.Domain.WebLog;
import com.farvision.common.api.CommonResult;
import com.farvision.common.api.ResultCode;
import com.farvision.common.config.ApiContext;
import com.farvision.common.exception.ServiceException;
import io.swagger.annotations.ApiOperation;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 统一日志处理切面
 * Created by macro on 2018/4/26.
 */
@Aspect
@Component
@Order(1)
public class WebLogAspect {
    private static final Logger LOGGER = LoggerFactory.getLogger(WebLogAspect.class);

    @Autowired(required = false)
    private ApiContext apiContext;

    @Pointcut("execution(public * mesweb.mesweb.controller..*.*(..))")
    public void webLog() {
    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        //RequestContextHolder：持有上下文的Request容器,获取到当前请求的request
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest httpServletRequest = sra.getRequest();
        //获取多租户的id
        String tenantid = httpServletRequest.getHeader("tenant_id");
        if (tenantid != null && tenantid.length() != 0)
        {
            apiContext.setCurrentTenantId(Long.parseLong(tenantid));
        }
    }

    @AfterReturning(value = "webLog()", returning = "ret")
    public void doAfterReturning(Object ret) throws Throwable {

    }

    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        //获取当前请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //记录请求信息
        WebLog webLog = new WebLog();
        Object result  = null;
        try {
            result = joinPoint.proceed();
            Signature signature = joinPoint.getSignature();
            MethodSignature methodSignature = (MethodSignature) signature;
            Method method = methodSignature.getMethod();
            if (method.isAnnotationPresent(ApiOperation.class)) {
                ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
                webLog.setDescription(apiOperation.value());
            }
            long endTime = System.currentTimeMillis();
            String urlStr = request.getRequestURL().toString();
            webLog.setBasePath(StrUtil.removeSuffix(urlStr, URLUtil.url(urlStr).getPath()));
            webLog.setIp(request.getRemoteUser());
            webLog.setMethod(request.getMethod());
            webLog.setParameter(getParameter(method, joinPoint.getArgs()));
            //webLog.setResult(result);
            webLog.setSpendTime((int) (endTime - startTime));
            webLog.setStartTime(startTime);
            webLog.setUri(request.getRequestURI());
            webLog.setUrl(request.getRequestURL().toString());
            if (result instanceof CommonResult<?>) {
                CommonResult<?> newResult = (CommonResult<?>) result;
                newResult.setMessage(newResult.getMessage() + "\\r\\n" + JSONUtil.toJsonStr(webLog));
            }
            LOGGER.info("{}", JSONUtil.parse(webLog));
            return result;
        } catch (Exception ex) {
            ex.printStackTrace();
            if (ex instanceof ServiceException) {//业务失败的异常，如“账号或密码错误”
                ServiceException serviceException = (ServiceException)ex;
                CommonResult.errorsInfo(ResultCode.VALIDATE_FAILED.getCode(),serviceException.getMessage());
                return result;
            } else
                if (ex instanceof NoHandlerFoundException) {
                NoHandlerFoundException serviceException = (NoHandlerFoundException)ex;
                CommonResult.errorsInfo(ResultCode.FAILED.getCode(),serviceException.getMessage());
                return result;
            } else if (ex instanceof ServletException) {
                ServletException servletException = (ServletException)ex;
                CommonResult.errorsInfo(ResultCode.FAILED.getCode(),servletException.getMessage());
                return result;
            } else {
                Signature signature = joinPoint.getSignature();
                MethodSignature methodSignature = (MethodSignature) signature;
                Method method = methodSignature.getMethod();
                if (method.isAnnotationPresent(ApiOperation.class)) {
                    ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
                    webLog.setDescription(apiOperation.value());
                }
                long endTime = System.currentTimeMillis();
                String urlStr = request.getRequestURL().toString();
                webLog.setBasePath(StrUtil.removeSuffix(urlStr, URLUtil.url(urlStr).getPath()));
                webLog.setIp(request.getRemoteUser());
                webLog.setMethod(request.getMethod());
                webLog.setParameter(getParameter(method, joinPoint.getArgs()));
                //webLog.setResult(result);
                webLog.setDescription("接口描述: " + webLog.getDescription() + "; 错误信息: " + ex.getMessage());
                webLog.setSpendTime((int) (endTime - startTime));
                webLog.setStartTime(startTime);
                webLog.setUri(request.getRequestURI());
                webLog.setUrl(request.getRequestURL().toString());
                if (result instanceof CommonResult<?>) {
                    CommonResult<?> newResult = (CommonResult<?>) result;
                    newResult.setMessage(ex.getMessage() + "\\r\\n" + JSONUtil.toJsonStr(webLog));
                    return result;
                } else {
                    return CommonResult.failed(JSONUtil.toJsonStr(webLog));
                }
            }
        }
    }
    /**
     * 根据方法和传入的参数获取请求参数
     */
    private Object getParameter(Method method, Object[] args) {
        List<Object> argList = new ArrayList<>();
        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < parameters.length; i++) {
            //将RequestBody注解修饰的参数作为请求参数
            RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class);
            if (requestBody != null) {
                argList.add(args[i]);
            }
            //将RequestParam注解修饰的参数作为请求参数
            RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);
            if (requestParam != null) {
                Map<String, Object> map = new HashMap<>();
                String key = parameters[i].getName();
                if (!StringUtils.isEmpty(requestParam.value())) {
                    key = requestParam.value();
                }
                map.put(key, args[i]);
                argList.add(map);
            }
        }
        if (argList.size() == 0) {
            return null;
        } else if (argList.size() == 1) {
            return argList.get(0);
        } else {
            return argList;
        }
    }
}
